package com.code.wordhelper.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ggh
 * @date 2023/6/16
 */
public class PatternUtils {
    public static final Pattern BASE64_IMG_PATTERN = Pattern.compile("^data:image/(\\w+);base64,");

    private PatternUtils() {
    }

    public static String regex(String source, String regex) {
        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(source);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    public static String regex(String source, Pattern regexPattern, Integer idx) {
        Matcher matcher = regexPattern.matcher(source);
        if (matcher.find()) {
            return matcher.group(idx);
        }
        return null;
    }

    public static List<String> regexList(String source, String regex, Integer idx) {
        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(source);
        List<String> strs = null;
        if (matcher.find()) {
            while (matcher.find()) {
                strs.add(matcher.group(idx));
            }
        }
        return strs;
    }

    public static List<String> regexList(String source, Pattern regexPattern, Integer idx) {
        Matcher matcher = regexPattern.matcher(source);
        List<String> strs = null;
        if (matcher.groupCount() > 0) {
            strs = new ArrayList<>();
            while (matcher.find()) {
                strs.add(matcher.group(idx));
            }
        }
        return strs;
    }

    public static boolean match(String source, String regex) {
        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(source);
        return matcher.find();
    }

    public static boolean match(String source, Pattern regexPattern) {
        Matcher matcher = regexPattern.matcher(source);
        return matcher.find();
    }

    public static void main(String[] args) {
        System.out.println(match("[aaaaa[name]aa", "\\[([\\w]+)\\]"));
    }
}
